package io.wjc.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Spring security 权限认证配置类
 */
@Slf4j
@Configuration
//@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     *
     * authorizeRequests()，formLogin()、httpBasic()这三个方法返回的分别是
     * ExpressionUrlAuthorizationConfigurer、FormLoginConfigurer、HttpBasicConfigurer，
     * 他们都是SecurityConfigurer接口的实现类，分别代表的是不同类型的安全配置器。
     *
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .antMatchers("/help","/hello").permitAll() //这些请求无需验证

                .and()
                .authorizeRequests()
                .antMatchers("/order/list").hasAuthority("order:list")
                .antMatchers("/order/info2").hasAuthority("order:info2")
                .antMatchers( "/db/**").access("hasRole('ADMIN') and hasRole('DBA')")

                .anyRequest().authenticated()  //允许认证的用户进行访问

                .and()
                .csrf().disable()//默认开启，这里先显式关闭
                .formLogin()  //内部注册 UsernamePasswordAuthenticationFilter
                .loginPage("/login-view") //表单登录页面地址
                .loginProcessingUrl("/login")//form表单POST请求url提交地址，默认为/login
                .passwordParameter("password")//form表单用户名参数名
                .usernameParameter("username") //form表单密码参数名
//                .successForwardUrl("/login-success")  //登录成功跳转地址
                .failureForwardUrl("/error") //登录失败跳转地址
                //.defaultSuccessUrl()//如果用户没有访问受保护的页面，默认跳转到页面
                //.failureUrl()
                //.failureHandler(AuthenticationFailureHandler)
                //.successHandler(AuthenticationSuccessHandler)
                //.failureUrl("/login?error")
                .permitAll();//允许所有用户都有权限访问登录相关页面

    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}